package leetcode

import kotlinetc.println

//https://leetcode.com/problems/minimum-path-sum/
/**
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
 */
fun main(args: Array<String>) {
    //[1,3,1],
    //  [1,5,1],
    //  [4,2,1]
    val grid = arrayOf(
            intArrayOf(1, 3, 1),
            intArrayOf(1, 5, 1),
            intArrayOf(4, 2, 1)
    )

    minPathSum(grid = grid).println()
}


//DP
/**
既然是动态规划，那么先求到达每个点的最短距离，复用前面的计算结果
 */
fun minPathSum(grid: Array<IntArray>): Int {

    val m = grid.size
    val n = grid[0].size

    val dp = Array(m, { Array(n, { Int.MAX_VALUE }) })

    dp[0][0] = grid[0][0]

    for (i in 0 until m) {
        for (j in 0 until n) {
            //两个方向，右下

            //到达该点的最小距离产生在 从上一个点 上往下走，或者从左往右走,比较两者最小值

            var topBottomSum = Int.MAX_VALUE

            var leftRightSum = Int.MAX_VALUE
            if (j - 1 >= 0) {
                leftRightSum = dp[i][j - 1]
            }

            if (i - 1 >= 0) {
                topBottomSum = dp[i - 1][j]
            }

            //去除起始点
            if (i == 0 && j == 0) continue
            dp[i][j] = grid[i][j] + Math.min(topBottomSum, leftRightSum)
        }
    }

    return dp[m - 1][n - 1]

}